#include<iostream>
#include<vector>
#include<semaphore.h>
#include"Task.hpp"
#include<pthread.h>
using namespace std;

const int DefaultNum=10;

template<class T>
class RingQueue
{
private:
    void P(sem_t& sem)  //-
    {
        sem_wait(&sem);
    }

    void V(sem_t& sem)  //+
    {
        sem_post(&sem);
    }

public:
    RingQueue(int cap=DefaultNum)
    {
        cap_=cap;
        q.resize(cap_);

        pthread_mutex_init(&c_mutex,nullptr); 
        pthread_mutex_init(&p_mutex,nullptr);

        sem_init(&cdata_sem_,0,0);  
        sem_init(&pspace_sem_,0, cap_);
    }

    void Push(const T& in)  //生产者
    {
        P(pspace_sem_);   //减，只能先减，不能先加
        pthread_mutex_lock(&p_mutex);

        q[p_step_]=in;
        p_step_=(p_step_+1)%cap_;

        pthread_mutex_unlock(&p_mutex);
        V(cdata_sem_);  //加
    }

    void Pop(T& out)   //消费者
    {
        P(cdata_sem_);
        pthread_mutex_lock(&c_mutex); 

        out=q[c_step_];
        c_step_=(c_step_+1)%cap_;

        pthread_mutex_unlock(&c_mutex);
        V(pspace_sem_);
    }

    ~RingQueue()
    {
        pthread_mutex_destroy(&c_mutex);
        pthread_mutex_destroy(&p_mutex);

        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);
    }
private:
    vector<T> q;
    int cap_;

    pthread_mutex_t c_mutex;
    pthread_mutex_t p_mutex;

    sem_t cdata_sem_;
    sem_t pspace_sem_;

    int c_step_=0;
    int p_step_=0;
};
